<template>
  <div class="createHome">
    <div class="createHome_box">
      <h1 class="hello">创建房间</h1>
      <div class="createHome_form">
        <h3>您的昵称：</h3>
        <el-input placeholder="（必填）" v-model.trim="name" clearable> </el-input>
      </div>
      <div class="createHome_btn">
        <el-button type="info" plain @click="confirm" class="one">确认创建</el-button>
        <router-link to="/">
          <el-button type="info" plain>返回主页</el-button>
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import ADDRESS from '../assets/backendApi'

import { SET_USERNAME, SET_ROOMID } from '../store/events'

export default {
  name: 'CreateHome',
  data() {
    let name = window.localStorage.getItem('username')
    if (!name) name = ''
    return {
      name
    }
  },
  methods: {
    confirm() {
      if (this.name === '') {
        this.$modal({
          titie: '提示',
          content: '请填写昵称'
        })
      }
      if (this.name !== '') {
        fetch(ADDRESS.http + '/createRoom/create', {
          method: 'post',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify({
            userName: this.name
          })
        })
          .then(r => r.text())
          .then(d => {
            // console.log(d)
            d = JSON.parse(d)
            if (d.status === 200) {
              this.$store.dispatch(SET_USERNAME, {
                username: this.name
              })
              this.$store.dispatch(SET_ROOMID, {
                roomid: d.data.roomId
              })
              this.$router.push({
                path: '/home'
              })
              this.$toast.success('创建房间成功！')
            } else {
              this.$toast.error('创建房间失败！')
            }
          })
      }
    }
  }
}
</script>

<style scoped>
.createHome {
  max-width: 40rem;
  margin: auto;
  min-height: 100vh;
  text-align: center;
}
.createHome_box {
  width: 45rem;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.hello {
  margin-bottom: 4rem;
  font-size: 2.5rem;
}
.createHome_form h3 {
  display: inline-block;
  font-weight: 550;
  margin-right: 1rem;
  font-size: 1.4rem;
}
.el-input {
  max-width: 20rem;
}
.createHome_btn {
  text-align: center;
  margin-top: 4rem;
}
.one {
  margin-right: 1rem;
}
</style>
